package com.sali.file;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;

public class FileChunkedServer {
    public static void main(String[] args) throws IOException {
        int port = 8080;
        HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);

        server.createContext("/file", new FileHandler());
        server.setExecutor(null);
        server.start();
    }

    static class FileHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            File fileToSend = new File("/Users/zhanghang/Desktop/test4-left-8000.wav"); // 替换为实际文件路径

            if (fileToSend.exists() && fileToSend.isFile()) {
                // 设置响应头，指定使用chunked编码
                exchange.getResponseHeaders().set("Transfer-Encoding", "chunked");
                exchange.sendResponseHeaders(200, 0);

                OutputStream os = exchange.getResponseBody();
                byte[] buffer = new byte[1024];
                try (FileInputStream fis = new FileInputStream(fileToSend)) {
                    int bytesRead;
                    while ((bytesRead = fis.read(buffer)) != -1) {
                        os.write(Integer.toHexString(bytesRead).getBytes());
                        os.write("\r\n".getBytes());
                        os.write(buffer, 0, bytesRead);
                        os.write("\r\n".getBytes());
                        os.flush();
                    }
                }

                os.write("0\r\n\r\n".getBytes()); // 发送chunked数据结束标志
                os.close();
            } else {
                // 文件不存在，返回404错误
                exchange.sendResponseHeaders(404, 0);
                exchange.getResponseBody().close();
            }
        }
    }
}
